//
//  NSAnimationPlayer.m
//  sandbox
//
//  Created by 杨岑 on 1/10/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "MyAnimationGroup.h"
#import "MyAnimationGroupItem.h"


@implementation MyAnimationGroup
{
    NSMutableArray* _items;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _items = [NSMutableArray array];
    }
    return self;
}

- (void)addItem:(MyAnimationGroupItem*)item
{
    item.animation.delegate = self;
    [_items addObject:item];
}

- (BOOL)startAt:(NSInteger)index
{
    if (index < _items.count)
    {
        MyAnimationGroupItem* item = _items[_current];
        [item.animation startAnimation];
        return YES;
    }
    return NO;
}

- (void)animationDidEnd:(NSAnimation *)animation
{
    MyAnimationGroupItem* item = _items[_current];
    if (item.onFinished) item.onFinished(item);
    _current++;
    _playing = [self startAt:_current];
}

- (void)animationDidStop:(NSAnimation *)animation
{
    _playing = NO;
}

- (BOOL)animationShouldStart:(NSAnimation *)animation
{
    _playing = YES;
    MyAnimationGroupItem* item = _items[_current];
    if (item.onStart) item.onStart(item);
    return YES;
}

- (BOOL)start
{
    _current = 0;
    return [self startAt:_current];
}

@end
